<template>
  <div class="dashboard-container">
    <!-- 顶部欢迎区域 -->
    <el-card class="welcome-card" shadow="hover">
      <div class="welcome-content">
        <div class="welcome-text">
          <h2>欢迎回来！</h2>
          <p>闲鱼自动化管理系统实时监控</p>
        </div>
        <div class="welcome-actions">
          <div class="welcome-time">
            <el-icon :size="20"><Clock /></el-icon>
            <span>{{ currentTime }}</span>
          </div>
          <el-button 
            type="danger" 
            plain 
            size="small" 
            :icon="Delete" 
            @click="handleCleanOfflineClients"
          >
            清理离线客户端
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 核心统计卡片 -->
    <el-row :gutter="16" class="stats-row">
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%)">
              <el-icon :size="32"><Monitor /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ statistics.total_clients }}</div>
              <div class="stat-label">客户端总数</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%)">
              <el-icon :size="32"><Connection /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">
                {{ statistics.online_clients }}
                <span class="stat-sub">/ {{ statistics.online_rate }}%</span>
              </div>
              <div class="stat-label">在线客户端</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon" style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)">
              <el-icon :size="32"><UserFilled /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">
                {{ statistics.logged_in_clients }}
                <span class="stat-sub">/ {{ statistics.login_rate }}%</span>
              </div>
              <div class="stat-label">已登录客户端</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon" style="background: linear-gradient(135deg, #fa709a 0%, #fee140 100%)">
              <el-icon :size="32"><ChromeFilled /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ statistics.browser_running }}</div>
              <div class="stat-label">浏览器运行中</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 第二排统计 -->
    <el-row :gutter="16" class="stats-row">
      <el-col :xs="24" :sm="12" :md="8">
        <el-card class="stat-card secondary" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon-sm" style="background: #52c41a">
              <el-icon :size="24"><ShoppingCart /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-label">今日下单</div>
              <div class="stat-value-sm">{{ statistics.today_orders }}</div>
            </div>
          </div>
          <div class="stat-footer">
            总计: {{ statistics.total_orders }} 单
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="12" :md="8">
        <el-card class="stat-card secondary" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon-sm" style="background: #1890ff">
              <el-icon :size="24"><Search /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-label">今日搜索</div>
              <div class="stat-value-sm">{{ statistics.today_searches }}</div>
            </div>
          </div>
          <div class="stat-footer">
            总计: {{ statistics.total_searches }} 次
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="12" :md="8">
        <el-card class="stat-card secondary" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon-sm" style="background: #722ed1">
              <el-icon :size="24"><TrendCharts /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-label">系统运行</div>
              <div class="stat-value-sm">稳定</div>
            </div>
          </div>
          <div class="stat-footer">
            WebSocket: {{ wsConnected ? '已连接' : '未连接' }}
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 最近搜索记录 -->
    <el-row :gutter="16">
      <el-col :xs="24" :lg="16">
        <el-card class="search-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span><el-icon><Search /></el-icon> 最近搜索记录</span>
              <el-button type="primary" link @click="refreshSearches">
                <el-icon><Refresh /></el-icon>
              </el-button>
            </div>
          </template>
          
          <el-table
            :data="recentSearches"
            style="width: 100%"
            :show-header="true"
            size="default"
            v-loading="searchLoading"
          >
            <el-table-column prop="keyword" label="搜索关键词" min-width="150">
              <template #default="{ row }">
                <el-tag type="primary" effect="plain">{{ row.keyword }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="search_count" label="搜索次数" width="100" align="center">
              <template #default="{ row }">
                <el-tag type="success">{{ row.search_count }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="last_search_time" label="最近搜索时间" width="180">
              <template #default="{ row }">
                {{ formatTime(row.last_search_time) }}
              </template>
            </el-table-column>
          </el-table>

          <el-empty v-if="recentSearches.length === 0 && !searchLoading" description="暂无搜索记录" />
        </el-card>
      </el-col>

      <!-- 活动时间线 -->
      <el-col :xs="24" :lg="8">
        <el-card class="activity-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span><el-icon><Clock /></el-icon> 最近活动</span>
              <el-button type="primary" link @click="refreshActivities">
                <el-icon><Refresh /></el-icon>
              </el-button>
            </div>
          </template>
          
          <el-scrollbar height="400px" v-loading="activityLoading">
            <el-timeline>
              <el-timeline-item
                v-for="(activity, index) in activities"
                :key="index"
                :timestamp="formatTime(activity.time)"
                placement="top"
                :color="activity.color"
              >
                <el-card>
                  <div class="activity-item">
                    <div class="activity-title">{{ activity.title }}</div>
                    <div class="activity-desc">{{ activity.description }}</div>
                  </div>
                </el-card>
              </el-timeline-item>
            </el-timeline>
            
            <el-empty v-if="activities.length === 0 && !activityLoading" description="暂无活动记录" :image-size="80" />
          </el-scrollbar>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Clock, Monitor, Connection, UserFilled, ChromeFilled, 
  ShoppingCart, Search, TrendCharts, Refresh, Delete 
} from '@element-plus/icons-vue'
import { getStatistics, getRecentSearches, getActivityTimeline, cleanOfflineClients } from '@/api/dashboard'
import { websocketManager } from '@/utils/websocket'

defineOptions({
  name: 'Dashboard'
})

// ==================== Reactive Data ====================
const currentTime = ref('')
const wsConnected = ref(false)
const statistics = ref({
  total_clients: 0,
  online_clients: 0,
  logged_in_clients: 0,
  browser_running: 0,
  today_orders: 0,
  total_orders: 0,
  today_searches: 0,
  total_searches: 0,
  online_rate: 0,
  login_rate: 0
})

const recentSearches = ref([])
const searchLoading = ref(false)

const activities = ref([])
const activityLoading = ref(false)

// ==================== 时间更新 ====================
let timeInterval = null

function updateTime() {
  const now = new Date()
  const options = { 
    year: 'numeric', 
    month: '2-digit', 
    day: '2-digit',
    hour: '2-digit', 
    minute: '2-digit', 
    second: '2-digit',
    hour12: false
  }
  currentTime.value = now.toLocaleString('zh-CN', options)
}

// ==================== 数据加载 ====================
async function loadStatistics() {
  try {
    const res = await getStatistics()
    if (res.code === 200) {
      statistics.value = res.data
    }
  } catch (error) {
    console.error('加载统计数据失败:', error)
  }
}

async function loadRecentSearches() {
  searchLoading.value = true
  try {
    const res = await getRecentSearches(10)
    if (res.code === 200) {
      recentSearches.value = res.data || []
    }
  } catch (error) {
    console.error('加载搜索记录失败:', error)
  } finally {
    searchLoading.value = false
  }
}

async function loadActivities() {
  activityLoading.value = true
  try {
    const res = await getActivityTimeline(15)
    if (res.code === 200) {
      activities.value = res.data || []
    }
  } catch (error) {
    console.error('加载活动记录失败:', error)
  } finally {
    activityLoading.value = false
  }
}

// ==================== 刷新操作 ====================
function refreshSearches() {
  loadRecentSearches()
  ElMessage.success('已刷新搜索记录')
}

function refreshActivities() {
  loadActivities()
  ElMessage.success('已刷新活动记录')
}

// ==================== 清理离线客户端 ====================
async function handleCleanOfflineClients() {
  try {
    await ElMessageBox.confirm(
      '此操作将永久删除所有离线客户端的数据记录，是否继续？',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const res = await cleanOfflineClients()
    if (res.code === 200) {
      ElMessage.success(res.msg || '清理成功')
      // 重新加载统计数据
      await loadStatistics()
    } else {
      ElMessage.error(res.msg || '清理失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('清理离线客户端失败:', error)
      ElMessage.error('清理失败')
    }
  }
}

// ==================== 工具函数 ====================
function formatTime(timeStr) {
  if (!timeStr) return '-'
  const date = new Date(timeStr)
  const now = new Date()
  const diff = now - date
  
  // 1分钟内
  if (diff < 60000) {
    return '刚刚'
  }
  // 1小时内
  if (diff < 3600000) {
    return `${Math.floor(diff / 60000)} 分钟前`
  }
  // 今天
  if (date.toDateString() === now.toDateString()) {
    return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
  }
  // 其他
  return date.toLocaleString('zh-CN', { 
    month: '2-digit', 
    day: '2-digit',
    hour: '2-digit', 
    minute: '2-digit' 
  })
}

// ==================== WebSocket监听 ====================
function handleWebSocketStatus(connected) {
  wsConnected.value = connected
}

// ==================== 生命周期 ====================
onMounted(() => {
  // 初始化时间
  updateTime()
  timeInterval = setInterval(updateTime, 1000)
  
  // 加载数据
  loadStatistics()
  loadRecentSearches()
  loadActivities()
  
  // WebSocket状态
  wsConnected.value = websocketManager.isConnected()
  
  // 定时刷新统计数据（每30秒）
  const statsInterval = setInterval(loadStatistics, 30000)
  
  // 清理定时器
  onUnmounted(() => {
    clearInterval(timeInterval)
    clearInterval(statsInterval)
  })
})
</script>

<style scoped lang="scss">
.dashboard-container {
  padding: 20px;
  background: #f0f2f5;
  min-height: calc(100vh - 84px);
}

/* 欢迎卡片 */
.welcome-card {
  margin-bottom: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  
  :deep(.el-card__body) {
    padding: 30px;
  }
}

.welcome-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  h2 {
    margin: 0 0 8px 0;
    font-size: 28px;
    font-weight: 600;
  }
  
  p {
    margin: 0;
    opacity: 0.9;
    font-size: 14px;
  }
}

.welcome-actions {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 12px;
}

.welcome-time {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  opacity: 0.95;
}

/* 统计卡片行 */
.stats-row {
  margin-bottom: 20px;
}

/* 统计卡片 */
.stat-card {
  cursor: pointer;
  transition: all 0.3s ease;
  
  &:hover {
    transform: translateY(-5px);
  }
  
  :deep(.el-card__body) {
    padding: 20px;
  }
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  flex-shrink: 0;
}

.stat-icon-sm {
  width: 48px;
  height: 48px;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  flex-shrink: 0;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 28px;
  font-weight: 700;
  color: #333;
  line-height: 1.2;
}

.stat-value-sm {
  font-size: 24px;
  font-weight: 700;
  color: #333;
}

.stat-sub {
  font-size: 14px;
  color: #999;
  font-weight: 400;
  margin-left: 4px;
}

.stat-label {
  font-size: 14px;
  color: #666;
  margin-top: 4px;
}

.stat-footer {
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px solid #f0f0f0;
  font-size: 13px;
  color: #999;
}

/* 二级统计卡片 */
.stat-card.secondary {
  :deep(.el-card__body) {
    padding: 16px;
  }
}

/* 搜索记录卡片 */
.search-card {
  margin-bottom: 20px;
  
  :deep(.el-card__header) {
    padding: 16px 20px;
    background: #fafafa;
  }
}

/* 活动卡片 */
.activity-card {
  :deep(.el-card__header) {
    padding: 16px 20px;
    background: #fafafa;
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
  font-size: 15px;
  
  span {
    display: flex;
    align-items: center;
    gap: 8px;
  }
}

/* 活动项 */
.activity-item {
  .activity-title {
    font-weight: 500;
    margin-bottom: 4px;
    font-size: 14px;
  }
  
  .activity-desc {
    font-size: 12px;
    color: #999;
  }
}

/* 响应式 */
@media (max-width: 768px) {
  .dashboard-container {
    padding: 12px;
  }
  
  .welcome-content {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .stat-icon {
    width: 48px;
    height: 48px;
  }
  
  .stat-value {
    font-size: 22px;
  }
}
</style>
